package com.ruoyi.web.controller.system;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import javax.xml.crypto.Data;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.bo.CountNumBo;
import com.ruoyi.system.domain.bo.DataBo;
import com.ruoyi.system.domain.bo.Datas;
import com.ruoyi.system.domain.bo.YgBo;
import com.ruoyi.system.domain.vo.DataVo;
import com.ruoyi.system.domain.vo.YgVo;
import com.ruoyi.system.service.*;
import com.ruoyi.system.service.impl.JlServiceImpl;
import org.apache.ibatis.jdbc.Null;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 人选管理Controller
 *
 * @author ruoyi
 * @date 2025-04-25
 */
@RestController
@RequestMapping("/system/yg")
public class YgController extends BaseController
{
    @Autowired
    private IYgService ygService;
    @Autowired
    private IJlService jlService;
    @Autowired
    private IQdkbService qdkbService;
    @Autowired
    private IPqService pqService;
    @Autowired
    private IWdqdService wdqdService;
    @Autowired
    private IYgrecordService ygrecordService;
    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查询人选管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:yg:list')")
    @GetMapping("/list")
    public TableDataInfo list(YgVo ygVo)
    {
        SysUser sysUser = getLoginUser().getUser();
        boolean contains9 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==9L);
        boolean contains3OR4 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==3L || v.getRoleId()==4L);
        boolean contains6 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==6L);
        boolean contains1OR2=true;
        if(sysUser.getRoles()!=null && sysUser.getRoles().size()!=0){
            contains1OR2 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==1L || v.getRoleId()==2L);
        }
        if(contains9){
            ygVo.setUserId(getUserId());
        }else if(contains3OR4){
            ygVo.setTlId(getUserId());
        }else if(contains6){
            ygVo.setPmId(getUserId());
        }else if(!contains1OR2){
            return getDataTable(new ArrayList<>());
        }
        List<CountNumBo> countNumBos = ygService.selectcountNum(ygVo);
        startPage();
        List<YgBo> list = ygService.selectYgList(ygVo);
        return getDataTable(list,countNumBos);
    }


    @PreAuthorize("@ss.hasPermi('system:yg:list')")
    @GetMapping("/listData")
    public AjaxResult list(DataVo dataVo){
        SysUser sysUser = getLoginUser().getUser();
        boolean contains3OR4 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==3L || v.getRoleId()==4L);
        if(contains3OR4){
            SysUser user=new SysUser();
            user.setDeptId(getDeptId());
            List<SysUser> sysUsers = sysUserService.selectUserList(user);
            Long [] userIds=sysUsers.stream().map(v->v.getUserId()).toArray(Long[]::new);
            dataVo.setUserIds(userIds);
        }
        List<DataBo> dataBos = ygService.selectcountNumTwo(dataVo);
        if(dataBos==null || dataBos.size()==0){
            return AjaxResult.success();
        }
        Map<String,Integer> mapNum=new HashMap<>();
        Map<Long,String> mapUser=new HashMap<>();

        for(DataBo d:dataBos){
            mapNum.put(d.getUserId()+"_"+d.getStatusTwo(),d.getNum());
            mapUser.put(d.getUserId(),d.getUserName());
        }
        if(contains3OR4){
            Long [] userIds1=  mapUser.keySet().toArray(new Long[mapUser.size()]);
            dataVo.setUserIds(userIds1);
        }
        Map<Long,Integer> mapbackNum=new HashMap<>();
        List<DataBo> dataBos1 = ygService.selectcountNumTwoF(dataVo);
        for(DataBo d:dataBos1){
            mapbackNum.put(d.getUserId(),d.getNum());
        }
        System.out.println(mapbackNum.get(105L)+"====>");
        List<Datas> list=new ArrayList<>();
        Datas data=new Datas();
        Integer one=0;
        Integer two=0;
        Integer three=0;
        Integer four=0;
        Integer five=0;
        Integer six=0;
        Integer seven=0;
        Integer totalNum=0;
        Integer totalbackNum=0;
        for(Long userId:mapUser.keySet()){
            Datas datas=new Datas();
            datas.setUserName(mapUser.get(userId));
            Integer backNum = mapbackNum.get(userId);
            datas.setBackNum(backNum!=null ? backNum : 0);
            Integer num1 = mapNum.get(userId + "_" + "1");
            datas.setSone(num1!=null ? num1 : 0);
            Integer num2 = null;
            datas.setStwo(num2!=null ? num2 : 0);
            Integer num3 = mapNum.get(userId + "_" + "3");
            datas.setSthree(num3 != null ? num3 : 0);

            Integer num4 = mapNum.get(userId + "_" + "4");
            datas.setSfour(num4 != null ? num4 : 0);

            Integer num5 = mapNum.get(userId + "_" + "5");
            datas.setSfive(num5 != null ? num5 : 0);

            Integer num6 = mapNum.get(userId + "_" + "6");
            datas.setSsix(num6 != null ? num6 : 0);

            Integer num7 = mapNum.get(userId + "_" + "7");
            datas.setSseven(num7 != null ? num7 : 0);
            datas.setStotal(datas.getSone() + datas.getStwo() +
                    datas.getSthree() + datas.getSfour() +
                    datas.getSfive() + datas.getSsix() + datas.getSseven()
            );

            one += datas.getSone();
            two += datas.getStwo();
            three += datas.getSthree();
            four += datas.getSfour();
            five += datas.getSfive();
            six += datas.getSsix();
            seven += datas.getSseven();
            totalNum += datas.getStotal();
            totalbackNum += datas.getBackNum();
            list.add(datas);
        }

        data.setUserName("总计");
        data.setSone(one);
        data.setStwo(two);
        data.setSthree(three);
        data.setSfour(four);
        data.setSfive(five);
        data.setSsix(six);
        data.setSseven(seven);
        data.setStotal(totalNum);
        data.setBackNum(totalbackNum);
        list.add(0,data);
        return AjaxResult.success(list);
    }




    @PreAuthorize("@ss.hasPermi('system:yg:list')")
    @GetMapping("/list/jl")
    public List<Jl> listJL()
    {
        SysUser sysUser = getLoginUser().getUser();
        boolean contains3OR4OR9 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==3L || v.getRoleId()==4L || v.getRoleId()==9L);
        LambdaQueryWrapper<Jl> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Jl::getTel,Jl::getJlId,Jl::getExpectationCity,Jl::getExpectationJop,Jl::getName,Jl::getSex,Jl::getYearBirth,Jl::getEducational);
        lambdaQueryWrapper.eq(contains3OR4OR9,Jl::getDeptId,getDeptId());
        lambdaQueryWrapper.orderByDesc(Jl::getJlId);
        return jlService.list(lambdaQueryWrapper);
    }

    @PreAuthorize("@ss.hasPermi('system:yg:list')")
    @GetMapping("/getOne/one")
    public AjaxResult getOne(YgVo ygVo)
    {
        LambdaQueryWrapper<Yg> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Yg::getStatusOne,Yg::getStatusTwo);
        lambdaQueryWrapper.eq(Yg::getYgId,ygVo.getYgId());
        lambdaQueryWrapper.eq(Yg::getStatusOne,"1");
        lambdaQueryWrapper.eq(Yg::getStatusTwo,ygVo.getStatusTwo());
        Yg dyg = ygService.getOne(lambdaQueryWrapper);
        if(dyg==null){
            throw new RuntimeException("该数据已有最新状态请重新刷新数据");
        }
        return AjaxResult.success();
    }



    /**
     * 导出人选管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:yg:export')")
    @Log(title = "人选管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, YgVo ygVo)
    {
        SysUser sysUser = getLoginUser().getUser();
        boolean contains9 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==9L);
        boolean contains3OR4 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==3L || v.getRoleId()==4L);
        boolean contains6 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==6L);
        if(contains9){
            ygVo.setUserId(getUserId());
        }else if(contains3OR4){
            ygVo.setTlId(getUserId());
        }else if(contains6){
            ygVo.setPmId(getUserId());
        }
        List<YgBo> list = ygService.selectYgList(ygVo);
        list.forEach(v -> v.setPositionAndbrand("【" + v.getBrandName() + "】-"+v.getPositionName()));
        ExcelUtil<YgBo> util = new ExcelUtil<YgBo>(YgBo.class);
        util.exportExcel(response, list, "人选管理数据");
    }

    /**
     * 获取人选管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:yg:query')")
    @GetMapping(value = "/{ygId}")
    public AjaxResult getInfo(@PathVariable("ygId") String ygStatus)
    {
         String[] s = ygStatus.split("_");
         Long ygId=Long.parseLong(s[0]);
         if(s!=null &&s.length==2){
             LambdaQueryWrapper<Yg> lambdaQueryWrapper=new LambdaQueryWrapper<>();
             lambdaQueryWrapper.select(Yg::getYgId);
             lambdaQueryWrapper.eq(Yg::getYgId,ygId);
             lambdaQueryWrapper.eq(Yg::getStatusTwo,s[1]);
              Yg dbYg = ygService.getOne(lambdaQueryWrapper);
              if(dbYg==null){
                  throw  new RuntimeException("该数据已有状态不一致请重新刷新数据");
              }
         }
        return success(ygService.selectYgByYgId(ygId));
    }

    /**
     * 新增人选管理
     */
    @PreAuthorize("@ss.hasPermi('system:yg:add')")
    @Log(title = "人选管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody YgVo ygVo)
    {
        LambdaQueryWrapper<Qdkb> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.select(Qdkb::getQdkbId);
        lambdaQueryWrapper.eq(Qdkb::getQdkbId,ygVo.getQdkbId());
        lambdaQueryWrapper.eq(Qdkb::getInterviewdeadline,"N");
        Qdkb dbQdkb = qdkbService.getOne(lambdaQueryWrapper);
        if(dbQdkb==null){
            throw new RuntimeException("面试已经截止");
        }

        LambdaQueryWrapper<Wdqd> lambdaQueryWrapper2=new LambdaQueryWrapper();
        lambdaQueryWrapper2.select(Wdqd::getOrderId);
        lambdaQueryWrapper2.eq(Wdqd::getOrderId,ygVo.getOrderId());
        lambdaQueryWrapper2.eq(Wdqd::getStatus,"1");
        Wdqd dbWdqd = wdqdService.getOne(lambdaQueryWrapper2);
        if(dbWdqd==null){
            throw new RuntimeException("单子已经释放,请重新抢单");
        }

        Date newTime=new Date();
        LambdaQueryWrapper<Pq> lambdaQueryWrapper1=new LambdaQueryWrapper();
        lambdaQueryWrapper1.select(Pq::getScheduleId);
        lambdaQueryWrapper1.eq(Pq::getOrderId,ygVo.getOrderId());
        lambdaQueryWrapper1.eq(Pq::getUserId,getUserId());
        lambdaQueryWrapper1.le(Pq::getScheduleStartDate,newTime);
        lambdaQueryWrapper1.ge(Pq::getScheduleEndDate,newTime);
        lambdaQueryWrapper1.last("limit 1");
        Pq dbPq = pqService.getOne(lambdaQueryWrapper1);
        if(dbPq==null){
            throw new RuntimeException("当前还未排期");
        }


        Jl jl=tranferBo(ygVo,Jl.class);
        SysUser sysUser = getLoginUser().getUser();
        boolean contains3OR4OR9 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==3L || v.getRoleId()==4L || v.getRoleId()==9L);
        if(contains3OR4OR9){
            jl.setDeptId(getDeptId());
        }
        Yg yg =tranferBo(ygVo,Yg.class);
        Date nowDate = DateUtils.getNowDate();

        yg.setEliminationTime(extendDate(nowDate,2));
        yg.setCreateTime(nowDate);
        yg.setUpdateTime(nowDate);
        yg.setUserId(getUserId());
        ygVo.setUserName(getUsername());
        return toAjax(ygService.insertYg(jl,yg,ygVo));
    }

    /**
     * 修改人选管理
     */
    @PreAuthorize("@ss.hasPermi('system:yg:edit')")
    @Log(title = "人选管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional
    public AjaxResult edit(@RequestBody YgVo ygVo)
    {
        LambdaQueryWrapper<Yg> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(Yg::getStatusOne,Yg::getStatusTwo,Yg::getStatusThree);
        lambdaQueryWrapper.eq(Yg::getYgId,ygVo.getYgId());
        lambdaQueryWrapper.eq(Yg::getStatusOne,"1");
        lambdaQueryWrapper.eq(Yg::getStatusTwo,ygVo.getStartStatusTwo());
        Yg dyg = ygService.getOne(lambdaQueryWrapper);
        if(dyg==null){
            throw new RuntimeException("该数据已有状态不一致请重新刷新数据");
        }
        if((dyg.getStatusTwo().equals("6") || dyg.getStatusTwo().equals("7")) && ygVo.getStatusOne().equals("2")){
            throw new RuntimeException("入职或者离职不能淘汰");
        }

        if(!ygVo.getStatusTwo().equals("1") && !ygVo.getStatusTwo().equals("2")){
            SysUser sysUser = getLoginUser().getUser();
            boolean contains6 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==6L);
            boolean contains1OR2=true;
            if(sysUser.getRoles()!=null && sysUser.getRoles().size()!=0){
                contains1OR2 = sysUser.getRoles().stream().anyMatch(v->v.getRoleId()==1L || v.getRoleId()==2L);
            }
            if(!contains6 && !contains1OR2){
                throw new RuntimeException("没有操作权限");
            }
        }

        if(ygVo.getStatusOne().equals("1")){
            if(ygVo.getIsSend()!=null && ygVo.getIsSend().equals("1")){
                System.out.println("发送短信");
            }
            if(ygVo.getStatusTwo().equals("2")){
                ygVo.setEliminationTime(extendDate(ygVo.getInterviewTime(),2));
            }
            if(ygVo.getStatusTwo().equals("3")){
                ygVo.setEliminationTime(extendDate(ygVo.getArrivalTime(),4));
            }
        }
        if(ygVo.getIndex().equals("3")){
            if(ygVo.getStatusTwo().equals("6")){
                ygVo.setEntryTime(new Date());
            }
            if(ygVo.getStatusTwo().equals("7")){
                ygVo.setResignationTime(new Date());
            }
        }
        int i = ygService.updateYg(ygVo);
        Ygrecord ygrecord=new Ygrecord();
        ygrecord.setYgId(ygVo.getYgId());
        ygrecord.setUserId(getUserId());
        ygrecord.setUserName(getUsername());
        ygrecord.setStatusOne(ygVo.getStatusOne());
        ygrecord.setStatusTwo(ygVo.getStatusTwo());
        ygrecord.setStatusThree(ygVo.getStatusThree());
        if(ygVo.getIndex().equals("1")){
            ygrecordService.insertYgrecord(ygrecord);
        }else if(ygVo.getIndex().equals("2") && !dyg.getStatusThree().equals(ygVo.getStatusThree())){

            ygrecordService.insertYgrecord(ygrecord);
        }else if(ygVo.getIndex().equals("3")) {

            ygrecordService.insertYgrecord(ygrecord);
        }

        return toAjax(i);
    }

    /**
     * 删除人选管理
     */
    @PreAuthorize("@ss.hasPermi('system:yg:remove')")
    @Log(title = "人选管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ygIds}")
    public AjaxResult remove(@PathVariable Long[] ygIds)
    {
        return toAjax(ygService.deleteYgByYgIds(ygIds));
    }
}
